package com.xuzhijie.pms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuzhijie.pms.common.Constants;
import com.xuzhijie.pms.common.Result;
import com.xuzhijie.pms.entity.Notice;
import com.xuzhijie.pms.entity.Role;
import com.xuzhijie.pms.entity.vo.NoticeVo;
import com.xuzhijie.pms.exception.PmsServerException;
import com.xuzhijie.pms.mapper.NoticeMapper;
import com.xuzhijie.pms.service.INoticeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuzhijie.pms.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 许志杰
 * @since 2024-02-13
 */
@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements INoticeService {

    @Resource
    private NoticeMapper mapper;

    @Override
    public Result findPage(Integer page, Integer size, Date startTime, Date endTime,String status) {
        Page<Notice> noticePage = new Page<>(page,size);
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<>();
        Page<Notice> result;
        Long total;
        if (startTime != null && endTime != null){
            queryWrapper.between("create_time",startTime,endTime);
        }
        if (!status.equals("0")){
            queryWrapper.eq("status",Integer.parseInt(status));
        }

        try {
            result = page(noticePage,queryWrapper);
            total = count(queryWrapper);
        }catch (Exception e){
            e.printStackTrace();
            throw new PmsServerException("业务繁忙", Constants.SYSTEM_ERROR);
        }
        List<NoticeVo> volist = new ArrayList<>();
        List<Notice> records = result.getRecords();
        for (Notice record : records) {
            NoticeVo noticeVo = new NoticeVo(record);
            noticeVo.setCreator(ThreadLocalUtil.getCurrentUser().getName());
            volist.add(noticeVo);
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("records",volist);
        resultMap.put("total",total);

        return Result.success(resultMap);
    }

    @Override
    public Result addNotice(NoticeVo noticevo) {

        if (BeanUtil.isEmpty(noticevo)){
            return Result.error();
        }
        Notice notice = new Notice();
        BeanUtil.copyProperties(noticevo,notice,"status");
        notice.setStatus(noticevo.getStatus().equals("true")?1:2);
        notice.setCreator(ThreadLocalUtil.getCurrentUser().getId());
        int insert = mapper.insert(notice);

        return Result.success(insert);
    }
}
